import React, { useState } from "react";
import {
  Space,
  Table,
  Tag,
  Popconfirm,
  Button,
  Modal,
  Input,
  Form,
} from "antd";
import type { TableProps } from "antd";
import { DeleteOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons";

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  id?: number | string;
  tags: string[];
}

const News: React.FC = () => {
  const [data, setData] = useState<DataType[]>([
    {
      key: "1",
      name: "John Brown",
      age: 32,
      id: 1,
      address: "New York No. 1 Lake Park",
      tags: ["nice", "developer"],
    },
    {
      key: "2",
      name: "Jim Green",
      age: 42,
      id: 2,
      address: "London No. 1 Lake Park",
      tags: ["loser"],
    },
    {
      key: "3",
      name: "Joe Black",
      age: 32,
      id: 3,
      address: "Sydney No. 1 Lake Park",
      tags: ["cool", "teacher"],
    },
  ]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<DataType | null>(null);

  const [form] = Form.useForm<DataType>();

  // 将事件处理函数移到组件内部
  const delNews = (row: DataType) => {
    console.log(row, "删除");
    // 这里可以添加实际删除逻辑
    setData(data.filter((item) => item.key !== row.key));
  };

  const cancel = (e: any) => {
    console.log(e, "取消");
  };

  // 正确的方式：通过闭包访问 state
  const showModal = (record: DataType) => {
    console.log(record, "编辑-新增");
    setSelectedRecord(record);
    if (record) {
      // 将数字类型的 age 转为字符串
      form.setFieldsValue({
        ...record,
        age: record.age, // 确保 age 是字符串类型
      });
    } else {
      form.resetFields(); // 重置表单
    }

    setIsModalOpen(true);
  };

  const handleOk = () => {
    // 提交表单时获取值
    form.validateFields().then((values) => {
      console.log("提交的值:", values);

      // 这里可以添加更新数据的逻辑
      if (selectedRecord && selectedRecord.key) {
        const updatedData = data.map((item) => {
          if (item.key === selectedRecord?.key) {
            return {
              ...item,
              ...values,
              age: values.age, // 将字符串转回数字
            };
          }
          return item;
        });

        setData(updatedData);

        console.log("编辑");
      } else {
        // 新增记录
        const newRecord: DataType = {
          ...values,
          key: new Date().getTime().toString(), // 使用 useId 生成唯一 key
          tags: ["nice", "developer"],
        };
        setData([...data, newRecord]);

        console.log("新增");
      }

      console.log("selectedRecord:", selectedRecord);

      form.resetFields(); // 重置表单
      setIsModalOpen(false);
      setSelectedRecord(null);
    });
  };

  const handleCancel = () => {
    form.resetFields(); // 关闭时重置表单
    setIsModalOpen(false);
    setSelectedRecord(null);
  };

  // 在组件内部定义 columns，以便访问内部状态和函数
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "Age",
      dataIndex: "age",
      key: "age",
    },
    {
      title: "Address",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "Tags",
      key: "tags",
      dataIndex: "tags",
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.length > 5 ? "geekblue" : "green";
            if (tag === "loser") {
              color = "volcano";
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            ghost
            icon={<EditOutlined />}
            iconPosition={"end"}
            // 正确方式：通过箭头函数传递 record 并调用内部函数
            onClick={() => showModal(record)}
          >
            Edit
          </Button>

          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => delNews(record)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger icon={<DeleteOutlined />} iconPosition={"end"}>
              Delete
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 字段值更新时触发回调事件;
  const onFormLayoutChange = (changedValues: any, allValues: any) => {
    console.log("表单值变化:", changedValues, allValues);
  };

  return (
    <div>
      <div>
        <div style={{ marginBottom: 20 }}>新闻列表</div>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          iconPosition={"end"}
          onClick={() => showModal({} as DataType)}
          style={{ marginBottom: 10 }}
        >
          add
        </Button>
      </div>
      <Table<DataType>
        columns={columns}
        dataSource={data}
        pagination={{ position: ["bottomCenter"] }}
        bordered={true}
      />

      <Modal
        title={selectedRecord?.id ? `编辑` : "新增"}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        {selectedRecord ? (
          <>
            <Form
              form={form}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 16 }}
              layout="horizontal"
              onValuesChange={onFormLayoutChange}
              style={{ maxWidth: 600, paddingTop: 20 }}
            >
              <Form.Item label="Name" name="name">
                <Input />
              </Form.Item>
              <Form.Item label="Age" name="age">
                <Input />
              </Form.Item>
              <Form.Item label="Address" name="address">
                <Input />
              </Form.Item>
            </Form>
          </>
        ) : (
          <p>Loading...</p>
        )}
      </Modal>
    </div>
  );
};

export default News;
